import json
import os
import uuid
from datetime import datetime

from django.core.paginator import Paginator
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
# 开发框架中通过中间件默认是需要登录态的，如有不需要登录的，可添加装饰器login_exempt
# 装饰器引⼊ from blueapps.account.decorators import login_exempt
from award_declaration.models import Organization, Award
from blueapps import account
from blueapps.account.models import User

def home(request):
    """
    ⾸⻚
    """
    return render(request, 'award_declaration/index_home.html')

def organization(request):
    """
    组织管理⾸⻚
    """
    return render(request, 'award_declaration/organization/index.html')

def award(request):
    """
    奖项管理⾸⻚
    """
    return render(request, 'award_declaration/award/index.html')

def batch_copy(request):
    """
    批量克隆⾸⻚
    """
    return render(request, 'award_declaration/award/copy.html')

def get_org_list(request):
    """
    获取组织信息列表数据
    """
    # 获取操作次数
    draw = int(request.GET.get("draw"))
    # 获取起始位置
    start = int(request.GET.get("start"))
    organizations = Organization.objects.all()
    total = len(organizations)
    page_length = int(request.GET.get("length"))
    page = start / page_length + 1

    paginator = Paginator(organizations, page_length)
    organizations = paginator.get_page(page)
    result_data = []
    for organization_item in organizations:
        result_data.append(
            {
                "id": organization_item.id,
                "org_name": organization_item.org_name,
                "principal":",".join(organization_item.principal.values_list("username", flat=True)),
                "apply_person":",".join(organization_item.apply_person.values_list("username", flat=True)),
                "operator": organization_item.operator,
                "create_time": organization_item.create_time.strftime("%Y-%m-%d%H:%M:%S"),
            }
        )
    return JsonResponse(
        {
            "result": True, "code": 200,
            "data": {
                "info": {
                    'data': result_data,
                    "recordsTotal": total,
                    "recordsFiltered": total,
                    "draw": draw,
                }
            }
        }
    )

def get_org_info_by_id(request, org_id):
    """
    获取编辑的数据
    """
    try:
        org_info = Organization.objects.get(id=int(org_id))
        return JsonResponse(
            {
                "result": True, "code": 200,
                "data": {
                    "info": {
                        'data':
                            {
                                "id": org_info.id,
                                "org_name": org_info.org_name,
                                "principal":",".join(org_info.principal.values_list("username", flat=True)),
                                "apply_person": ",".join(org_info.apply_person.values_list("username",flat=True))
                            }
                        }
                    }
            }
        )
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "获取数据失败"})


def save_org_info(request):
    """
    保存组织信息
    """
    operator = request.user.username
    org_name = request.POST.get("org_name")
    principal_user_list = request.POST.get("principal").split(",")
    apply_person_list = request.POST.get("apply_person").split(",")

    users_model_object = account.get_user_model()
    users = users_model_object.objects.values_list("username", flat=True)
    need_add_principal_list = list(set(principal_user_list).difference(set(users)))

    org_id = request.POST.get("org_id", None)
    if org_id:
        # 修改数据
        try:
            with transaction.atomic():
            org_obj = Organization.objects.get(id=int(org_id))
            Organization.objects.filter(id=org_id).update(**{"org_name":org_name, "operator": operator})
        # 负责⼈关系维护
        for username in need_add_principal_list:
            user = users_model_object(username=username, is_staff=True)
            user.save()
        # 负责⼈关系维护
        # 1.清空旧的关系
        org_obj.principal.clear()
        # 2.新建与负责⼈关系
 
org_obj.principal.set(users_model_object.objects.filter(username__in=principal_user_list))
        # 组织信息与可申报⼈关系
        users = users_model_object.objects.values_list("username",flat=True)
        need_add_apply_person_list =list(set(apply_person_list).difference(set(users)))
        for username in need_add_apply_person_list:
            user = users_model_object(username=username, is_staff=True)
            user.save()
        # 可申报⼈关系维护
        # 1.清空旧的可申报⼈关系
        org_obj.apply_person.clear()
        # 2.新建与可申报⼈关系
 
org_obj.apply_person.set(users_model_object.objects.filter(username__in=apply_person_list))
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "error"})
    else:
        # 新增数据
        try:
            with transaction.atomic():
                # 组织名称是否存在
                if Organization.objects.filter(org_name=org_name):
                    return JsonResponse({"result": False, "code": 101, "message": "该组织名称已存在，⽆需添加"})
                organization = Organization(org_name=org_name, operator=operator)
                organization.save()
                # 负责⼈关系维护
                for username in need_add_principal_list:
                    user = users_model_object(username=username, is_staff=True)
                    user.save()
                # 添加组织与负责⼈对应关系
 
organization.principal.set(users_model_object.objects.filter(username__in=principal_user_list))
                # 可申报⼈关系维护
                users = users_model_object.objects.values_list("username",flat=True)
                need_add_apply_person_list =list(set(apply_person_list).difference(set(users)))
                for username in need_add_apply_person_list:
                    user = users_model_object(username=username, is_staff=True)
                    user.save()
                # 添加组织与申报⼈对应关系
 
organization.apply_person.set(users_model_object.objects.filter(username__in=apply_person_list))
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "error"})
    return JsonResponse({"result": True, "code": 200, "message": "success"})

def delete_org_info(request, org_id):
    """
    删除数据
    """
    try:
        with transaction.atomic():
            org_obj = Organization.objects.get(id=int(org_id))
            org_obj.principal.clear()
            org_obj.apply_person.clear()
            org_obj.delete()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "删除数据失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )